import { app, BrowserWindow, globalShortcut, Menu } from "electron";
import { join } from "path";
import startIpc from "./ipc/index";
import { getMenus } from "./menu";
import { catchWeb, isDev, PATH } from "./utils";

if (process.platform === "win32") app.setAppUserModelId(app.getName());
if (!app.requestSingleInstanceLock()) {
  app.quit();
  process.exit(0);
}

let win;

const createWindow = () => {
  win = new BrowserWindow({
    icon: join(PATH.public, "favicon.ico"),
    width: 1300 + 50,
    height: 800 + 50,
    resizable: false,
    transparent: true,
    frame: false, // 无边框
    autoHideMenuBar: true, // 隐藏menu
    webPreferences: {
      preload: PATH.preload,
      webSecurity: false, //解决跨域
      nodeIntegration: true,
      contextIsolation: false,
    },
  });
  Menu.setApplicationMenu(getMenus(win));
  // 如果打包了，渲染index.html
  if (isDev()) {
    win.loadURL(PATH.url);
  } else {
    win.loadFile(PATH.indexHtml);
  }
  startIpc(win);
  catchWeb(win);
};

app
  .whenReady()
  .then(() => {
    globalShortcut.register("F11", () => {
      return false;
    });
  })
  .then(() => {
    createWindow(); // 创建窗口
    app.on("activate", () => {
      if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
  });

// 关闭窗口
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});
